package com.onegene.pdf.component.report.colon;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.layout.RootLayoutArea;
import com.itextpdf.layout.property.*;
import com.onegene.pdf.component.AbstractReportBuilder;
import com.onegene.pdf.component.IReportBuilder;
import com.onegene.pdf.component.entity.EarlyReportBean;
import com.onegene.pdf.component.entity.ParaExtraParam;
import com.onegene.pdf.component.event.ColonHeaderTextEvent;
import com.onegene.pdf.component.event.PageNumberEvent;
import com.onegene.pdf.component.factory.ReportBuilderContext;
import com.onegene.pdf.component.paint.CancerPainting;
import com.onegene.pdf.component.report.CommonHandler;
import com.onegene.pdf.component.report.cancer.CancerTenReportBuilder;
import com.onegene.pdf.util.BarCodeUtil;
import com.onegene.pdf.util.Precondition;
import org.springframework.util.StringUtils;

import java.net.MalformedURLException;
import java.util.Date;
import java.util.List;

/**
 * @author: laoliangliang
 * @description: 早筛报告开发（易长安，常壹宁）
 * @create: 2020/8/4 10:14
 **/
public class ColonReportBuilder extends AbstractReportBuilder {

    private ColonHeaderTextEvent headerTextEvent;
    private PageNumberEvent pageEvent;
    private String[][] cyn = {{"Bio-A(FIT)", "fit"}, {"Bio-B", "biob"}, {"Bio-C", "bioc"}, {"Bio-D", "biod"}};
    private String[][] yca = {{"Bio-A(FIT)", "fit"}, {"Bio-B", "biob"}, {"Bio-C", "bioc"}, {"Bio-D", "biod"}};

    public ColonReportBuilder(ReportBuilderContext builderContext) {
        super(builderContext);
    }

    /**
     * @return true-肠癌 false-胃癌
     */
    private boolean isChangAi(Integer version) {
        return version == 1 || version == 2;
    }

    @Override
    public IReportBuilder addIndex() {
        doc.setFontSize(11);
        doc.setFontColor(ColonColor.getFontBlackColor());
        String code = earlyReportBean.getCode();
        if ("changaizscyn".equals(code)) {
            earlyReportBean.setTitle("常壹宁-" + earlyReportBean.getSampleCode());
            earlyReportBean.setTitleHeader("无创肠癌早期筛查检测报告");
            earlyReportBean.setSampleType("CYN");
        } else if ("changaizs".equals(code)) {
            earlyReportBean.setTitle("易长安-" + earlyReportBean.getSampleCode());
            earlyReportBean.setTitleHeader("结直肠癌早期筛查检测报告");
            earlyReportBean.setSampleType("YCA");
        } else if ("ymlgjqtb".equals(code) || "ymlgjqt".equals(code)) {
            earlyReportBean.setTitle("胃癌致病菌-" + earlyReportBean.getSampleCode());
            earlyReportBean.setTitleHeader("胃癌高危致病菌分型检测报告");
            earlyReportBean.setSampleType("WA");
        } else if ("ymlgjyyn".equals(code)) {
            earlyReportBean.setTitle("优壹宁-" + earlyReportBean.getSampleCode());
            earlyReportBean.setTitleHeader("无创胃癌致病菌筛查及用药指导检测报告");
            earlyReportBean.setSampleType("YYN");
        }
        // 添加logo
        if (!"WA".equals(earlyReportBean.getSampleType())) {
            PageSize pageSize = pdf.getDefaultPageSize();
            Image logoImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/colon/logo.png")));
            logoImage.setFixedPosition(pageSize.getWidth() - 100, pageSize.getHeight() - 73);
            logoImage.setHeight(28).setWidth(60);
            doc.add(logoImage);
        }

        Integer version = builderContext.getVersion();
        Image typeImage = null;
        if (version == 1) {
            typeImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/colon/CYNtit.png")));
        } else if (version == 2) {
            typeImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/colon/YCAtit.png")));
        } else if (version == 3) {
            typeImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/colon/logo.png")));
        } else if (version == 4) {
            typeImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/hp/tit.png")));
        }
        Precondition.checkNotNull(typeImage, "version类型不存在" + version);
        typeImage.setMarginTop(100);
        typeImage.setHeight(25f);
        typeImage.setHorizontalAlignment(HorizontalAlignment.CENTER);
        doc.add(typeImage);

        Paragraph p1 = new Paragraph(earlyReportBean.getTitleHeader());
        p1.setFontSize(25f);
        p1.setTextAlignment(TextAlignment.CENTER);
        p1.setMarginTop(10);
        doc.add(p1);
        Image indexImage;
        if (isChangAi(version)) {
            indexImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/colon/1.png")));
        } else {
            indexImage = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/hp/1.png")));
        }
        indexImage.setHorizontalAlignment(HorizontalAlignment.CENTER);
        indexImage.setWidth(100f);
        if (isChangAi(version)) {
            indexImage.setHeight(94.5f);
        } else {
            indexImage.setHeight(100f);
        }
        indexImage.setMarginTop(15);
        doc.add(indexImage);

        Table table = new Table(2);
        table.setMarginTop(70);
        table.setHorizontalAlignment(HorizontalAlignment.CENTER);
        table.setWidth(UnitValue.createPercentValue(60));
        table.startNewRow();
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("受检人")));
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(earlyReportBean.getName())));
        table.startNewRow();
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("样本编号")));
        String prefixPath = builderContext.getPrefixPath();
        if (prefixPath.endsWith("/")) {
            prefixPath = prefixPath.substring(0, prefixPath.length() - 1);
        }
        prefixPath = prefixPath.substring(0, prefixPath.lastIndexOf("/"));
        String path = prefixPath + "/" + earlyReportBean.getSampleCode() + ".png";
        BarCodeUtil.getBarCode(earlyReportBean.getSampleCode(), path);
        Image barImage = null;
        try {
            barImage = new Image(ImageDataFactory.create(path));
            barImage.scale(0.6f, 0.6f);
            barImage.setHorizontalAlignment(HorizontalAlignment.CENTER);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(barImage).add(new Paragraph(earlyReportBean.getSampleCode())));
        table.startNewRow();
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("收样日期")));
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(earlyReportBean.getReceiveTime())));
        table.startNewRow();
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("报告日期")));
        table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(earlyReportBean.getAuditTime())));
        if (!StringUtils.isEmpty(earlyReportBean.getThirdPartyName())) {
            table.startNewRow();
            table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("送检单位")));
            table.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(earlyReportBean.getThirdPartyName())));
        }
        doc.add(table);

        Table slogan = new Table(4);
        slogan.setWidth(UnitValue.createPercentValue(50));
        slogan.setBorder(Border.NO_BORDER);
        slogan.setMarginTop(80);
        slogan.setHorizontalAlignment(HorizontalAlignment.CENTER);
        slogan.startNewRow();
        slogan.addCell(new Cell().addStyle(ColonStyle.getSloganCell()).add(new Paragraph("无创").setFontColor(ColonColor.getThemeColor())));
        if (isChangAi(version)) {
            slogan.addCell(new Cell().addStyle(ColonStyle.getSloganCell()).add(new Paragraph("早期").setFontColor(ColonColor.getThemeColor())));
        } else {
            slogan.addCell(new Cell().addStyle(ColonStyle.getSloganCell()).add(new Paragraph("全面").setFontColor(ColonColor.getThemeColor())));
        }
        slogan.addCell(new Cell().addStyle(ColonStyle.getSloganCell()).add(new Paragraph("精准").setFontColor(ColonColor.getThemeColor())));
        slogan.addCell(new Cell().addStyle(ColonStyle.getSloganCell()).add(new Paragraph("方便").setFontColor(ColonColor.getThemeColor())));
        doc.add(slogan);
        return this;
    }

    @Override
    public IReportBuilder addHello() {
        return null;
    }

    @Override
    public IReportBuilder addExaminee() {
        doc.setMargins(50, 53, 39, 53);
        Style pageStyle = new Style();
        pageStyle.setFontColor(ColonColor.getThemeColor());
        pageStyle.setFontSize(12);
        pageEvent = new PageNumberEvent(doc, -1, pageStyle);
        pdf.addEventHandler(PdfDocumentEvent.START_PAGE, pageEvent);

        // 受检人信息
        headerTextEvent = new ColonHeaderTextEvent(font, isChangAi(builderContext.getVersion()));
        pdf.addEventHandler(PdfDocumentEvent.START_PAGE, headerTextEvent);
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        Paragraph title1 = new Paragraph();
        title1.add(new Text("受检人信息")).addStyle(ColonStyle.getTitleStyle());
        doc.add(title1);

        Table examTable = new Table(2);
        examTable.setMarginTop(2);
        examTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
        examTable.setWidth(UnitValue.createPercentValue(95));
        examTable.setBorder(new SolidBorder(ColonColor.getThemeColor(), 0.5f));
        examTable.startNewRow();
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("姓 名：" + earlyReportBean.getName()).addStyle(ColonStyle.getExamineeCellParagraph().setPaddingTop(10))));
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("性 别：" + ("FAMALE".equals(earlyReportBean.getGender()) ? "女" : "MALE".equals(earlyReportBean.getGender()) ? "男" : "")).addStyle(ColonStyle.getExamineeCellParagraph().setPaddingTop(10))));
        examTable.startNewRow();
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("年 龄：" + (earlyReportBean.getExamineeBirthYear() == null ? "" : (DateUtil.year(new Date()) - earlyReportBean.getExamineeBirthYear()))).addStyle(ColonStyle.getExamineeCellParagraph())));
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("样本编号：" + earlyReportBean.getSampleCode()).addStyle(ColonStyle.getExamineeCellParagraph())));
        examTable.startNewRow();
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("样本类型：粪便样本").addStyle(ColonStyle.getExamineeCellParagraph())));
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("收样日期：" + earlyReportBean.getReceiveTime()).addStyle(ColonStyle.getExamineeCellParagraph())));
        examTable.startNewRow();
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("样本质控结果：合格").addStyle(ColonStyle.getExamineeCellParagraph().setPaddingBottom(10))));
        examTable.addCell(new Cell().addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("报告日期：" + earlyReportBean.getAuditTime()).addStyle(ColonStyle.getExamineeCellParagraph().setPaddingBottom(10))));
        doc.add(examTable);

        if (isChangAi(builderContext.getVersion())) {
            // 检测结果
            Paragraph title2 = new Paragraph();
            title2.setMarginTop(15);
            title2.add(new Text("检测结果")).addStyle(ColonStyle.getTitleStyle());
            doc.add(title2);

            doc.add(new Paragraph("经检测和综合判定，受检者的结直肠癌筛查结果为："));
            Paragraph result = new Paragraph();
            Style style = new Style();
            if ("阴性".equals(earlyReportBean.getSampleResult())) {
                style.setBorder(new SolidBorder(ColonColor.getThemeColor(), 2f));
                style.setFontColor(ColonColor.getThemeColor());
            } else if ("阳性".equals(earlyReportBean.getSampleResult())) {
                style.setBorder(new SolidBorder(ColonColor.getRedColor(), 2f));
                style.setFontColor(ColonColor.getRedColor());
            } else if ("弱阳性".equals(earlyReportBean.getSampleResult())) {
                style.setBorder(new SolidBorder(ColonColor.getYellowColor(), 2f));
                style.setFontColor(ColonColor.getYellowColor());
            }
            style.setFontSize(16.5f);
            style.setBold();
            style.setHorizontalAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.MIDDLE);
            style.setTextAlignment(TextAlignment.CENTER);
            style.setPaddings(0, 0, 5, 0);
            style.setWidth(100f);
            style.setBorderRadius(new BorderRadius(12, 12));
            result.addStyle(style);
            result.add(new Text(earlyReportBean.getSampleResult()));
            doc.add(result);
            doc.add(new Paragraph(earlyReportBean.getDescription().replaceAll("\n", "")).setTextAlignment(TextAlignment.CENTER));

            // 检测指标
            Paragraph title3 = new Paragraph();
            title3.setMarginTop(15);
            title3.add(new Text("检测指标")).addStyle(ColonStyle.getTitleStyle());
            doc.add(title3);
            doc.add(new Paragraph("经检测，受检者粪便样本中各项指标的检测结果如下："));

            Table content = new Table(5);
            content.setMarginTop(10);
            content.setWidth(UnitValue.createPercentValue(95));
            content.setHorizontalAlignment(HorizontalAlignment.CENTER);
            content.startNewRow();
            content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("检测内容")));
            if ("CYN".equals(earlyReportBean.getSampleType())) {
                for (int i = 0; i < cyn.length; i++) {
                    String contentTitle = cyn[i][0];
                    content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(contentTitle)));
                }
            } else {
                for (int i = 0; i < yca.length; i++) {
                    String contentTitle = yca[i][0];
                    content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(contentTitle)));
                }
            }
            content.startNewRow();
            content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph("检测结果")));
            String fit = earlyReportBean.getFit();
            if ("CYN".equals(earlyReportBean.getSampleType())) {
                for (int i = 0; i < cyn.length; i++) {
                    String contentTitle = cyn[i][1];
                    Object fieldsValue = ReflectUtil.getFieldValue(earlyReportBean, contentTitle);
                    if (("++".equals(fit) || "+++".equals(fit)) && "Bio-A".equals(cyn[i][0])) {
                        content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(fieldsValue != null ? fieldsValue.toString() : "").setFontColor(ColonColor.getRedColor())));
                    } else {
                        content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(fieldsValue != null ? fieldsValue.toString() : "")));
                    }
                }
            } else {
                for (int i = 0; i < yca.length; i++) {
                    String contentTitle = yca[i][1];
                    Object fieldsValue = ReflectUtil.getFieldValue(earlyReportBean, contentTitle);
                    content.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(new Paragraph(fieldsValue != null ? fieldsValue.toString() : "")));
                }
            }
            doc.add(content);

            // 结果说明
            Paragraph desc = new Paragraph();
            desc.setMarginTop(15);
            desc.setFirstLineIndent(20);
            desc.setFontSize(10);
            desc.add(new Text("结果说明：").setFontColor(ColonColor.getThemeColor()));
            String text = "根据受检者粪便样本中结直肠癌相关标志物（粪便隐血、癌症驱动基因突变和抑癌基因的甲基化水平）的检测结果，采用壹基因结直肠癌早筛分类模型，综合判定受检者的粪便样本的检测结果为" + earlyReportBean.getSampleResult() + "。";
            desc.add(new Text(text));
            doc.add(desc);
        } else {
            // 检测结果
            Paragraph title2 = new Paragraph();
            title2.setMarginTop(5);
            title2.add(new Text("检测结果")).addStyle(ColonStyle.getTitleStyle());
            doc.add(title2);

            Table checkResult = new Table(4);
            checkResult.setWidth(UnitValue.createPercentValue(75));
            checkResult.setHorizontalAlignment(HorizontalAlignment.CENTER);
            checkResult.startNewRow();
            checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getNormalParagraph("幽门螺杆菌感染")));
            checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getNormalParagraph(("高危型"))));
            checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getNormalParagraph(("克拉霉素耐药"))));
            checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getNormalParagraph(("左氧氟沙星耐药"))));
            checkResult.startNewRow();
            if ("YYN".equals(earlyReportBean.getSampleType())) {
                boolean isYang = "阳性".equals(earlyReportBean.getSampleResults().getSampleResult());
                if (isYang) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph((earlyReportBean.getSampleResults().getSampleResult())).setFontColor(ColonColor.getYellowColor())));
                } else {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph((earlyReportBean.getSampleResults().getSampleResult())).setFontColor(ColonColor.getThemeColor())));
                }
                if (isYang && "是".equals(earlyReportBean.getSampleResults().getCagA())) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getCagA()).setFontColor(ColonColor.getRedColor())));
                } else {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getCagA()).setFontColor(ColonColor.getThemeColor())));
                }
                if (isYang && "耐药型".equals(earlyReportBean.getSampleResults().getClarith())) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getClarith()).setFontColor(ColonColor.getYellowColor())));
                } else {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getClarith()).setFontColor(ColonColor.getThemeColor())));
                }
                if (isYang && "耐药型".equals(earlyReportBean.getSampleResults().getLevofloxacin())) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getLevofloxacin()).setFontColor(ColonColor.getYellowColor())));
                } else {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getLevofloxacin()).setFontColor(ColonColor.getThemeColor())));
                }
            }
            if ("WA".equals(earlyReportBean.getSampleType())) {
                boolean isYing = "阴性".equals(earlyReportBean.getSampleResults().getSampleResult());
                boolean isYang = "阳性".equals(earlyReportBean.getSampleResults().getSampleResult());
                if (isYing) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph((earlyReportBean.getSampleResults().getSampleResult())).setFontColor(ColonColor.getThemeColor())));
                }else{
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph((earlyReportBean.getSampleResults().getSampleResult())).setFontColor(ColonColor.getYellowColor())));
                }
                if ("是".equals(earlyReportBean.getSampleResults().getCagA())) {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getCagA()).setFontColor(ColonColor.getRedColor())));
                } else {
                    checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getCagA()).setFontColor(ColonColor.getThemeColor())));
                }
                if (!StringUtils.isEmpty(earlyReportBean.getSampleResults().getClarith())) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getClarith())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getClarith()).setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getClarith()).setFontColor(ColonColor.getThemeColor())));
                    }
                } else if (isYing) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getClarith())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("无须检测").setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("无须检测").setFontColor(ColonColor.getThemeColor())));
                    }
                } else if (isYang) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getClarith())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("建议检测").setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("建议检测").setFontColor(ColonColor.getThemeColor())));
                    }
                }
                if (!StringUtils.isEmpty(earlyReportBean.getSampleResults().getLevofloxacin())) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getLevofloxacin())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getLevofloxacin()).setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph(earlyReportBean.getSampleResults().getLevofloxacin()).setFontColor(ColonColor.getThemeColor())));
                    }
                } else if (isYing) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getLevofloxacin())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("无须检测").setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("无须检测").setFontColor(ColonColor.getThemeColor())));
                    }
                } else if (isYang) {
                    if ("耐药型".equals(earlyReportBean.getSampleResults().getLevofloxacin())) {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("建议检测").setFontColor(ColonColor.getYellowColor())));
                    } else {
                        checkResult.addCell(new Cell().addStyle(ColonStyle.getDefaultCell()).add(ColonComponent.getResultParagraph("建议检测").setFontColor(ColonColor.getThemeColor())));
                    }
                }
            }

            doc.add(checkResult);
            doc.add(new Paragraph(earlyReportBean.getDescription().replaceAll("\n", "")).setTextAlignment(TextAlignment.CENTER));
            // 检测指标
            Paragraph title3 = new Paragraph();
            title3.setMarginTop(0);
            title3.add(new Text("检测指标")).addStyle(ColonStyle.getTitleStyle());
            doc.add(title3);
            doc.add(new Paragraph("经检测，受检者粪便样本中胃癌致病性幽门螺杆菌各项指标的检测结果如下：").setFirstLineIndent(18).setMarginTop(0));

            com.itextpdf.layout.element.List list = new com.itextpdf.layout.element.List();
            Image symbol1 = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/hp/s1.png")));
            float size = 11;
            symbol1.setWidth(size);
            symbol1.setHeight(size);
            symbol1.setMarginRight(4);
            symbol1.setMarginBottom(-1f);
            symbol1.setMarginLeft(18);
            ListItem item1 = new ListItem("幽门螺杆菌检测").setListSymbol(symbol1);
            list.add(item1);
            doc.add(list);

            Table tab1 = new Table(3);
            tab1.setMarginTop(5);
            tab1.setMarginBottom(5);
            tab1.setWidth(UnitValue.createPercentValue(89));
            tab1.startNewRow();
            tab1.setHorizontalAlignment(HorizontalAlignment.CENTER);
            tab1.addHeaderCell(ColonComponent.getHeaderCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 0.5f)).add(new Paragraph("检测内容")));
            tab1.addHeaderCell(ColonComponent.getHeaderCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 0.5f)).add(new Paragraph("检测基因")));
            tab1.addHeaderCell(ColonComponent.getHeaderCell().add(new Paragraph("检测结果")));
            tab1.addCell(ColonComponent.getDefaultThemeCell(2, 1).add(new Paragraph("幽门螺杆菌")));
            tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("16S RNA基因")));
            tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph(earlyReportBean.getRna_16s())));
            tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("23S RNA基因")));
            tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph(earlyReportBean.getRna_23s())));
            if (!"未检测".equals(earlyReportBean.getCagA())) {
                tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("高危型幽门螺杆菌")));
                tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("CagA基因")));
                if (!StringUtils.isEmpty(earlyReportBean.getCagA())) {
                    tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph(earlyReportBean.getCagA())));
                } else if ("阴性".equals(earlyReportBean.getSampleResult())) {
                    tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("无须检测")));
                } else if ("阳性".equals(earlyReportBean.getSampleResult())) {
                    tab1.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("建议检测")));
                }
            }
            doc.add(tab1);

            com.itextpdf.layout.element.List list2 = new com.itextpdf.layout.element.List();
            Image symbol2 = new Image(ImageDataFactory.create(CancerTenReportBuilder.class.getClassLoader().getResource("image/hp/s2.png")));
            symbol2.setWidth(size);
            symbol2.setHeight(size);
            symbol2.setMarginRight(4);
            symbol2.setMarginBottom(-1f);
            symbol2.setMarginLeft(18);
            list2.add(new ListItem("幽门螺杆菌的耐药检测").setListSymbol(symbol2));
            doc.add(list2);

            Table tab2 = new Table(3);
            tab2.setMarginTop(5);
            tab2.setMarginBottom(5);
            tab2.setWidth(UnitValue.createPercentValue(89));
            tab2.startNewRow();
            tab2.setHorizontalAlignment(HorizontalAlignment.CENTER);
            tab2.addHeaderCell(ColonComponent.getHeaderCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 0.5f)).add(new Paragraph("药物")));
            tab2.addHeaderCell(ColonComponent.getHeaderCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 0.5f)).add(new Paragraph("检测基因")));
            tab2.addHeaderCell(ColonComponent.getHeaderCell().add(new Paragraph("检测结果")));
            tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("克拉霉素")));
            tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("23S RNA基因")));
            if (!StringUtils.isEmpty(earlyReportBean.getClarith())) {
                tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph(earlyReportBean.getClarith())));
            } else if ("阴性".equals(earlyReportBean.getSampleResult())) {
                tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("无须检测")));
            } else if ("阳性".equals(earlyReportBean.getSampleResult())) {
                tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("建议检测")));
            }
            if (!"未检测".equals(earlyReportBean.getLevofloxacin())) {
                tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("左氧氟沙星")));
                tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("GyrA基因")));
                if (!StringUtils.isEmpty(earlyReportBean.getLevofloxacin())) {
                    tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph(earlyReportBean.getLevofloxacin())));
                } else if ("阴性".equals(earlyReportBean.getSampleResult())) {
                    tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("无须检测")));
                } else if ("阳性".equals(earlyReportBean.getSampleResult())) {
                    tab2.addCell(ColonComponent.getDefaultThemeCell().add(new Paragraph("建议检测")));
                }
            }
            doc.add(tab2);
            doc.add(new Paragraph("注： “+”代表检测到幽门螺杆菌相应的特异性基因序列或靶标位点，“-”代表未检测到。").setFirstLineIndent(25).setFontSize(9f));
        }

        // 签名
        Table sign = new Table(1);
        sign.setWidth(UnitValue.createPercentValue(30));
        sign.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        sign.setMarginRight(20);
        sign.startNewRow();
        float offy = 0f;
        sign.addCell(new Cell().setPaddings(offy, 0, offy, 0).addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("检测人：" + earlyReportBean.getTestPersonnel())));
        sign.startNewRow();
        sign.addCell(new Cell().setPaddings(offy, 0, offy, 0).addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("审核人：" + earlyReportBean.getAuditor())));
        sign.startNewRow();
        sign.addCell(new Cell().setPaddings(offy, 0, offy, 0).addStyle(ColonStyle.getExamineeCell()).add(new Paragraph("审核日期：" + earlyReportBean.getAuditTime())));
        doc.add(sign);

        RootLayoutArea layoutArea = (RootLayoutArea) doc.getRenderer().getCurrentArea();
        Rectangle bBox = layoutArea.getBBox();

        // 画印章
        CancerPainting cancerPainting = new CancerPainting(pdf, font);
        cancerPainting.drawStamper(bBox, builderContext, 42, -28, 120);
        cancerPainting.close();

        // 声明
        if (isChangAi(builderContext.getVersion())) {
            doc.add(new Paragraph("声明：检测结果只对本次送检样本负责，结果不能直接作为确诊结直肠疾病/结直肠癌症的依据，仅供临床参考，不代表临床诊断意见。").setFontSize(10).setMarginTop(10));
        } else {
            doc.add(new Paragraph("结果声明：本检测结果仅对本次送检样本负责，且仅供临床参考，需临床医师结合受检者胃部健康状况做进一步处理。").setFontSize(9f));
        }

        return this;
    }

    @Override
    public IReportBuilder addDetectionContent() {
        return null;
    }

    @Override
    public IReportBuilder addResultSummary() {
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        Div resultDiv = new Div();
        Paragraph p1 = new Paragraph();
        p1.add(new Text("结果解读")).addStyle(ColonStyle.getTitleStyle());
        resultDiv.add(p1);
        java.util.List<IElement> iElements1 = getFixContent(earlyReportBean.getResultContent().getValue());
        ParaExtraParam extraParam = new ParaExtraParam(true, true);
        ParaExtraParam extraParamNoIndent = new ParaExtraParam(false, true);
        ParaExtraParam indentOffExtraParam = new ParaExtraParam(true, 4f, true);
        if (isChangAi(builderContext.getVersion())) {
            defaultHandlerHtml(resultDiv, iElements1, indentOffExtraParam);
        } else {
            defaultHandlerHtml(resultDiv, iElements1, extraParam);
        }
        doc.add(resultDiv);

        List<EarlyReportBean.ContentBean> content = earlyReportBean.getContent();
        for (EarlyReportBean.ContentBean contentBean : content) {
            if ("指标阅读指南".equals(contentBean.getLabel())) {
                addContext(contentBean, extraParam);
            }
            if ("检测方法".equals(contentBean.getLabel())) {
                if (!isChangAi(builderContext.getVersion())) {
                    doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                }
                addContext(contentBean, extraParam);
            }
        }
        for (EarlyReportBean.ContentBean contentBean : content) {
            if ("背景知识".equals(contentBean.getLabel())) {
                contentBean.setLabel("检测原理介绍");
                if (isChangAi(builderContext.getVersion())) {
                    addContext(contentBean, indentOffExtraParam);
                } else {
                    addContext(contentBean, extraParam);
                }
            }
            if ("健康小贴士".equals(contentBean.getLabel())) {
                if (isChangAi(builderContext.getVersion())) {
                    addContext(contentBean, indentOffExtraParam);
                }
            }
        }
        if (isChangAi(builderContext.getVersion())) {
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("规避危险因素-线下".equals(contentBean.getLabel())) {
                    addContext(contentBean, extraParamNoIndent);
                }
            }
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("改变不良习惯-线下".equals(contentBean.getLabel())) {
                    addContext(contentBean, extraParamNoIndent);
                }
            }
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("注意结直肠癌体征和症状-线下".equals(contentBean.getLabel())) {
                    addContext(contentBean, extraParamNoIndent);
                }
            }

        } else {
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("幽门螺杆菌是胃癌最重要的致病因素".equals(contentBean.getLabel())) {
                    doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                    addContext(contentBean, extraParam);
                }
            }
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("幽门螺杆菌常见问题解答-线下".equals(contentBean.getLabel())) {
                    contentBean.setLabel("常见问题解答");
                    addContext(contentBean, extraParamNoIndent);
                }
            }
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("健康小贴士".equals(contentBean.getLabel())) {
                    doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                    if (!isChangAi(builderContext.getVersion())) {
                        addContext(contentBean, extraParam);
                    }
                }
            }
            for (EarlyReportBean.ContentBean contentBean : content) {
                if ("预防幽门螺杆菌感染-线下".equals(contentBean.getLabel())
                        || "注意日常食疗养胃-线下".equals(contentBean.getLabel())
                        ) {
                    ParaExtraParam paraExtraParam = new ParaExtraParam(false, true);
                    paraExtraParam.setTitleFontSize(12f);
                    addContext(contentBean, paraExtraParam);
                }
            }
        }
        // 参考文献
        addLiteratures();
        return this;
    }

    private void addContext(EarlyReportBean.ContentBean contentBean) {
        addContext(contentBean, new ParaExtraParam());
    }

    private void addContext(EarlyReportBean.ContentBean contentBean, ParaExtraParam paraExtraParam) {
        Div blockDiv = new Div();
        blockDiv.setKeepTogether(true);
        Paragraph p3 = new Paragraph();
        p3.add(new Text(contentBean.getLabel().split("-")[0])).addStyle(ColonStyle.getTitleStyle().setFontSize(paraExtraParam.getTitleFontSize()));
        blockDiv.add(p3);
        java.util.List<IElement> iElements2 = getFixContent(contentBean.getValue());
        defaultHandlerHtml(blockDiv, iElements2, paraExtraParam);
        doc.add(blockDiv);
    }

    private void addLiteratures() {
        int number = 1;
        Div literatureDiv = new Div();
        Paragraph p4 = new Paragraph();
        p4.add(new Text("全球权威科研及参考文献(部分)")).addStyle(ColonStyle.getTitleStyle());
        literatureDiv.add(p4);
        literatureDiv.setKeepTogether(true);
        for (EarlyReportBean.LiteratureListBean listBean : earlyReportBean.getLiteratureList()) {
            Paragraph segment = new Paragraph();
            segment.setFixedLeading(14);
            segment.setMarginBottom(10);
            segment.setFontSize(9f).setFontColor(new DeviceRgb(85, 85, 85));
            segment.add(new Text("[" + (number++) + "]"));
            segment.add(new Text(listBean.getAuthor() + ". "));
            segment.add(new Text(listBean.getTitle() + ". "));
            segment.add(new Text(listBean.getJournal() + ". "));
            segment.add(new Text(listBean.getSerialNumber()));
            literatureDiv.add(segment);
        }
        doc.add(literatureDiv);
    }

    @Override
    public IReportBuilder addContext() {

        pdf.removeEventHandler(PdfDocumentEvent.START_PAGE, headerTextEvent);
        pdf.removeEventHandler(PdfDocumentEvent.START_PAGE, pageEvent);
        return null;
    }

    @Override
    public IReportBuilder addThanks() {
        return null;
    }

    @Override
    public IReportBuilder addBackCover() {
        return null;
    }

    @Override
    public IReportBuilder addCatalog() {
        return null;
    }

    @Override
    public IReportBuilder addPageNumber() {
        return null;
    }

    private java.util.List<IElement> getFixContent(String content) {
        content = content.replaceAll("<p(.*?)>", "<div>");
        content = content.replaceAll("</p>", "</div>");
        if (content.startsWith("<div>")) {
            content = content.replaceAll("<div>", "<div style='line-height:18pt;font-size:16px;'>");
        } else {
            content = "<div style='line-height:18pt;font-size:16px;'>" + content + "</div>";
        }
        return HtmlConverter.convertToElements(content, proper);
    }

    /**
     * 通过itext7转换html文本成元素组件后取出文本，自行组装成段落（Paragraph）
     * 优点：此方法优势在于可以大量减小PDF体积，数据越多可大约减少三分之二的大小
     * 缺点：目前只支持字体颜色及粗体两种html样式，后续若需要添加需要修改代码
     */
    private void handlerHtmlParagraph(Div overall, java.util.List<IElement> iElements) {
        Style style = new Style();
        style.setFontSize(11);
        style.setTextAlignment(TextAlignment.JUSTIFIED);
        style.setCharacterSpacing(0.7f);
        style.setMarginTop(0);
        style.setMarginBottom(0);
        Paragraph paragraph = new Paragraph().addStyle(style);
        paragraph.setFixedLeading(22f);
        for (IElement iElement : iElements) {
            CommonHandler.handlerElement(iElement, paragraph);
        }
        overall.add(paragraph);
    }

    private void defaultHandlerHtml(Div overall, java.util.List<IElement> iElements, ParaExtraParam paraExtraParam) {
        for (IElement iElement : iElements) {
            Style style = new Style();
            style.setFontSize(11);
            style.setTextAlignment(TextAlignment.JUSTIFIED);
            style.setCharacterSpacing(0.5f);
            if (iElement instanceof Div) {
                Div div = (Div) iElement;
                java.util.List<IElement> children = div.getChildren();
                // 全部段落改成相同样式
                CommonHandler.addParagraphStyleCircle(style, children, div, paraExtraParam);
                if (paraExtraParam.getLineHeightEnabled()) {
                    iElement.setProperty(Property.LINE_HEIGHT, LineHeight.createMultipliedValue(paraExtraParam.getLineHeight()));
                }
                overall.add(div);
            } else if (iElement instanceof Paragraph) {
                Paragraph element = (Paragraph) iElement;
                overall.add(element.addStyle(style));
            }
        }
    }
}
